from typing import List, Optional
from uuid import UUID

from sqlalchemy import update, delete
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select

from model import Tender


class TenderCRUD:
    def __init__(self, db: AsyncSession):
        self.db = db

    async def create(self, category: str, quarter: str) -> Tender:
        """创建一个新的 Tender"""
        new_tender = Tender(category=category, quarter=quarter)
        self.db.add(new_tender)
        await self.db.commit()
        await self.db.refresh(new_tender)
        return new_tender

    async def get_by_id(self, tender_id: UUID) -> Optional[Tender]:
        """根据 ID 获取一个 Tender"""
        result = await self.db.execute(select(Tender).where(Tender.id == tender_id))
        return result.scalar_one_or_none()

    async def get_all(self, skip: int = 0, limit: int = 100) -> List[Tender]:
        """获取所有 Tender（分页）"""
        result = await self.db.execute(select(Tender).offset(skip).limit(limit))
        return list(result.scalars().all())

    async def update(self, tender_id: UUID, category: Optional[str] = None, quarter: Optional[str] = None) -> Optional[Tender]:
        """更新一个 Tender 的字段"""
        stmt = update(Tender).where(Tender.id == tender_id)
        values = {}
        if category is not None:
            values["category"] = category
        if quarter is not None:
            values["quarter"] = quarter
        if values:
            stmt = stmt.values(**values).returning(Tender)
            result = await self.db.execute(stmt)
            await self.db.commit()
            return result.scalar_one_or_none()
        return None

    async def delete(self, tender_id: UUID) -> bool:
        """删除一个 Tender"""
        stmt = delete(Tender).where(Tender.id == tender_id)
        result = await self.db.execute(stmt)
        await self.db.commit()
        return result.rowcount > 0
